package cn.edu.zzu.demo04ThreadAdvance;

/**
 * 线程通信：
 * 信号灯法
 */
public class TestPC02 {
    public static void main(String[] args) {
        TV tv = new TV();
        new Player(tv).start();
        new Watcher(tv).start();
    }
}

/**
 * 演员
 */
class Player extends Thread {
    private TV tv;

    public Player(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            if (i % 2 == 0) {
                tv.show("快乐大本营播放中。。。");
            }else{
                tv.show("抖音：记录美好生活！");
            }

        }
    }
}

/**
 * 观众
 */
class Watcher extends Thread{
    private TV tv;

    public Watcher(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            tv.watch();
        }
    }
}

/**
 * TV
 */
class TV {
    private String voice;
    private boolean flag = true;

    public synchronized void show(String voice) {
        if (!flag) {
            //观看中
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //表演
        this.voice = voice;
        this.flag = !this.flag;

        System.out.println("演员表演了 "+ this.voice);

        //叫观众看
        this.notify();
    }

    public synchronized void watch() {
        if (flag) {
            //表演中
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //观看
        this.voice = voice;
        this.flag = !this.flag;

        System.out.println("观众观看了 "+this.voice);

        //看完了， 叫演员表演
        this.notify();
    }
}
